package com.example.demo1.controller;

import com.example.demo1.pojo.dto.orderCreateDto;
import com.example.demo1.pojo.dto.orderUpdateDto;
import com.example.demo1.pojo.order;
import com.example.demo1.pojo.result.result;
import com.example.demo1.service.orderService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/orders")
@Validated
@CrossOrigin(origins = "*")
public class orderController {
    @Autowired
    private orderService orderServices;

    @PostMapping
    public result<order> createOrder(@RequestBody @Valid orderCreateDto orderDto) {
        try {
            order order=orderServices.createOrder(orderDto);
            return result.success("order create success",order);
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public result<order> getOrder(@PathVariable Integer id) {
        try{
            Optional<order> orderOpt=orderServices.getOrderById(id);
            if(orderOpt.isPresent()){
                return result.success(orderOpt.get());
            }else{
                return result.error("order not exist");
            }
        }catch (Exception e){
            return result.error(e.getMessage());
        }
    }
    @PutMapping("/{id}")
    public result<order> updateOrder(
            @PathVariable Integer id,
            @Valid @RequestBody orderUpdateDto orderDto) {
        try {
            order order = orderService.updateOrder(id, orderDto);
            return result.success("订单更新成功", order);
        } catch (Exception e) {
            return result.error(e.getMessage());
        }
    }

    @GetMapping("/users/{userId}")
    public result<List<order>> getUserOrders(@PathVariable Integer userId) {
        try {
            List<order> orders = orderService.getUserOrders(userId);
            return result.success(orders);
        } catch (Exception e) {
            return result.error(e.getMessage());
        }
    }

    @GetMapping
    public result<List<order>> getAllOrders() {
        try {
            List<order> orders = orderService.getAllOrders();
            return result.success(orders);
        } catch (Exception e) {
            return result.error(e.getMessage());
        }
    }
}
